<?php

    class database
    {
        public static $iCountNormalQuery = 0;

        public $db = null;
        public $sSql = '';

        public function connect()
        {
            $this->db = mysql_pconnect(DB_HOST, DB_USERNAME, DB_PASSWORD);
            if(!$this->db)
            {
                echo "connect fail!";
                exit;
            }
            mysql_select_db(DB_NAME);
            mysql_query("SET NAMES utf8");
        }

        /** FUNCTION execute($strQuery)
        *   Execute a query and return $result
        *   To get resources of $aResult make step
        *   if(mysql_num_rows($aResult))
        *   {
        *       echo "<table>";
        *       while($row = mysql_fetch_array($aResult))
        *       {
        *           echo "<tr>";
        *           echo "<td>".$row['product_id']."</td>";
        *           ....
        *           echo "</tr>";
        *       }
        *       echo "</table>";
        *   }
        */
        public function execute($strQuery)
        {
            database::$iCountNormalQuery++;
            $this->sSql = $strQuery;
            $this->connect();
            $aResult = mysql_query($strQuery, $this->db);
            if($aResult)
            {
                return $aResult;
            }
            return false;
        }

        /** FUNCTION getObject($strQuery)
        *   $oProduct = $oDatabase->getObject("select * from product");
        *   echo "<h1>ID: ".$oProduct->name."</h1>";
        */
        public function getObject($strQuery)
        {
            $aResult = $this->execute($strQuery);
            if(mysql_num_rows($aResult))
            {
                $aRow = mysql_fetch_object($aResult);
                return $aRow;
            }
            return null;
        }

        /** FUNCTION getListObject($strQuery, $bId = false)
        *   default function $bId = false, if $bId = true, return key with primary key
        *   $aListProduct = $oDatabase->getListObject("select * from product");
        *   foreach($aListProduct as $key => $oProduct)
        *   {
        *       echo "<h1>Key $key value $oProduct->name</h1>";
        *       .....
        *   }
        *   
        *   To get an object in list from id.
        *   print_r($aListProduct['2']);
        *   note above 2 is ID not index.
        *   example a product has id is 4 get it from list
        *   $aListproducts[4]
        */
        public function getListObject($strQuery, $bId = false, $bArray = false)
        {
            $aResult = $this->execute($strQuery);
            if(mysql_num_rows($aResult))
            {
                $aList = array();
                $sFieldId = mysql_fetch_field($aResult,0)->name;
                if(!$bArray)
                {
                    while($row = mysql_fetch_object($aResult))
                    {
                        eval('$sId = $row->'.$sFieldId.";");
                        if($bId)
                        {
                            $aList[$sId] = $row;
                        }
                        else
                        {
                            array_push($aList, $row);
                        }    
                    }
                }
                else
                {
                    while($row = mysql_fetch_array($aResult))
                    {
                        eval('$sId = $row["'.$sFieldId.'"];');
                        if($bId)
                        {
                            $aList[$sId] = $row;
                        }
                        else
                        {
                            array_push($aList, $row);
                        }    
                    }
                }
                return $aList;
            }
            return array();
        }

        /** FUNCTION  getValue($strQuery)
        *   return a value from query like number, string
        *   note result is string so to use it you must pass to int or ....
        *   $iTotal = $oDatabase->getValue("select * from product where product_id = 12");
        *   echo "<h1>Total: $iTotal</h1>";
        */
        public function getValue($strQuery)
        {
            $aResult = $this->execute($strQuery);
            if(mysql_num_rows($aResult))
            {
                $aRow = mysql_fetch_row($aResult);
                if($aRow)
                {
                    return $aRow[0];
                }
                return null;
            }
            return null;
        }
        /** FUNCTION add
        *   add row into table
        *   example
        *   $aProduct = array(
        *       'name' = 'iphone5',
        *       'total' = 32
        *   );
        *   $oDatabase->add('product', $aData);
        */
        public function add($sTable = '', $aData = array())
        {
            $sFiedl = '';
            $sValue = '';
            foreach($aData as $key => $value)
            {
                $sFiedl = $sFiedl."$key,";
                $sValue = $sValue."'$value',";
            }
            $sFiedl = trim($sFiedl , ',');
            $sValue = trim($sValue , ',');
            $sSql = "INSERT INTO $sTable($sFiedl) VALUES($sValue);";
            $result = $this->execute($sSql);
            if($result)
            {
                $iId = mysql_insert_id();
                if($iId)
                {
                    return $iId;
                }
                else
                {
                    return true;
                }
            }
            return false;
        }

        /** FUNCTION delete($sTable = '', $aCondition = array())
        *   delete row from table
        *   $aCondition = array(
        *       'id > 20' => AND
        *       'id < 30' => ''
        *   );
        *   $oDatabase->delete('product', $aCondition);
        */
        public function delete($sTable = '', $aCondition = array())
        {
            $sCondition = '';
            if(is_array($aCondition))
            {
                if(count($aCondition))
                {
                    foreach($aCondition as $key => $value)
                    {
                        $sCondition = $sCondition . "$key $value ";
                    }
                }
            }
            else
            {
                $sCondition = $aCondition;
            }
            if(empty($sCondition))
            {
                $sCondition = 1;
            }
            $sSql = "DELETE FROM $sTable WHERE $sCondition";
            $result = $this->execute($sSql);
            return $result;
        }

        /** FUNCTION update($sTable = '', $aData = array(), $aCondition = array())
        *   update row in table
        *   $aCondition = array(
        *       'id> 20' => 'AND',
        *       'id < 10' => ''
        *   );
        *   $aData = array(
        *       'name' => 'trieu quang phuc',
        *       'total' => 3434
        *   );
        *   $oDatabase->update('product', $aData, $aCondition);
        */
        public function update($sTable = '', $aData = array(), $aCondition = array())
        {
            if(is_array($aCondition))
            {
                $sCondition = '';
                if(count($aCondition))
                {
                    foreach($aCondition as $key => $value)
                    {
                        $sCondition = $sCondition . "$key $value ";
                    }
                }
                else
                {
                    $sCondition = '1';
                }
            }
            else
            {
                $sCondition = $aCondition;
            }
            $sValue = '';
            foreach($aData as $key => $value)
            {
                $sValue = $sValue . "$key = '$value',";
            }
            $sValue = trim($sValue, ',');
            $sSql = "UPDATE $sTable SET $sValue WHERE $sCondition";
            $result = $this->execute($sSql);
            return $result;
        }

        /**
        *   FUNCTION check admin User 
        */
        public static function isAdmin($bDirect = false)
        {
            core::checkSession();
            if(!database::isUser())
            {
                if($bDirect)
                {
                    header('location:'. URL::getLink());
                }
                else
                {
                    return false;
                }
            }
            $oDatabase = new database();
            $sQeury = "select type from user where username = '".$_SESSION['username']."'";
            $sType = $oDatabase->getValue($sQeury);
            if($sType == 'admin')
            {
                return true;
            }
            if($bDirect)
            {
                header('location:'. URL::getLink());
                die;
            }
            else
            {
                return false;
            }
        }

        /**
        *   FUNCTION check user login or guess 
        */
        public static function isUser($bDirect = false)
        {
            core::checkSession();
            if(isset($_SESSION['username']))
            {
                return true;
            }
            if($bDirect)
            {
                header('location:'. URL::getLink());
                die;
            }
            else
            {
                return false;
            }
        }

        /**
        *   FUNCTION LOG 
        */
        public static function log($str = '')
        {
            $file = fopen("changelog/log.txt","a");
            fwrite($file,$str."\n");
            fclose($file);
        }

        /**
        *   FUNCTION ADD SETTING 
        */
        public static function setSetting($sSettingId, $sSettingValue, $sSettingKey = '',$sSettingType = '', $sSettingDescription = '')
        {
            $oDatabse = new database();
            $sQuery = "SELECT * FROM settings WHERE setting_id = '".$sSettingId."'";
            $result = $oDatabse->getListObject($sQuery);
            if(count($result) > 0)
            {
                $sQuery = "UPDATE settings SET setting_value = '".$sSettingValue."' ";
                if($sSettingKey != '')
                {
                    $sQuery = $sQuery. ",setting_key = '".$sSettingKey."' ";
                }
                if($sSettingKey != '')
                {
                    $sQuery = $sQuery. ",type = '".$sSettingType."' ";
                }
                if($sSettingKey != '')
                {
                    $sQuery = $sQuery. ",description = '".$sSettingDescription."' ";
                }
                $sQuery = $sQuery. "WHERE setting_id = '".$sSettingId."'";
                return $oDatabse->execute($sQuery);
            }
            else
            {
                $sQuery = "INSERT INTO settings VALUES('".$sSettingId."','".$sSettingKey."','".$sSettingValue."','".$sSettingType."','".$sSettingDescription."')";
                return $oDatabse->execute($sQuery);
            }
        }

        public static function getSetting($sSettingId)
        {
            $oDatabase = new database();
            $sQuery = "SELECT * FROM settings WHERE setting_id = '".$sSettingId."'";
            return $oDatabase->getObject($sQuery);
        }

        public static function getListSettings($sType)
        {
            $oDatabase = new database();
            $sQuery = "SELECT * FROM settings WHERE type = '".$sType."'";
            return $oDatabase->getListObject($sQuery,true,true);
        }

        public static function printVar($var)
        {
            echo '<textarea>';
            print_r($var);
            echo '</textarea>';
        }
        
        /**
        *   FUNCTION check user login or guess 
        */
        public static function login($sUsername, $sPassword)
        {
            core::checkSession();
            if(isset($_SESSION['username']))
            {
                return true;
            }
            
            $oDatabase = new database();
            $sQuery = "SELECT * FROM user WHERE username = '".$sUsername."' AND password = '".$sPassword."'";
            $oUser = $oDatabase->getObject($sQuery);
            if(!$oUser)
            {
                return false;
            }
            $_SESSION['username'] = $oUser->username;
            return true;
        }
        
        public function logout()
        {
            core::checkSession();
            if(isset($_SESSION['username']))
            {
                unset($_SESSION['username']);
            }
            URL::getLink('',true);
        }
    }

?>
